var express = require('express');
var router = express.Router();
var MongoClient=require('mongodb').MongoClient;
var DB_CONN_STR='mongodb://127.0.0.1:27017/meituan';
var async=require('async');

/* GET users listing. */
// 跨域请求
router.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/reg', function(req, res, next) {
  MongoClient.connect(DB_CONN_STR,function(err,db){
    if (err) {
      res.send('网络异常')
    }else{
      console.log('第一步,链接上mongo');
      var conn = db.collection('vue');
      async.series([
          //先做查询
          function(cb){
            conn.find({username:req.query.username}).count(function(err,num){
              if (err) {
                cb('err','查询失败');
              }else{
                if (num>0) {
                  cb('null','登录成功')
                }else{
                  cb(null)
                }
              }
            })
          },
          //做储存
          function(cb){
              conn.save(req.query,function(err,info){
                if (err) {
                  cb('err','新增成功')
                }else{
                  cb('null','注册成功')
                }
              })
          }
      ],function(err,result){
        if (err) {
          res.send(result);
        }else{
          res.send('成功')
        }
      })
    }
  })
});



module.exports = router;
